﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;

namespace SilenthinkCommon.ActionFilters
{
    public class ETagAttribute : ActionFilterAttribute
    {
        private readonly string template;
        private string filePath;
        public ETagAttribute(string template)
        {
            this.template = template;
        }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var request = filterContext.HttpContext.Request;

            if (request.Headers["Cache-Control"] == "no-cache")
            {
                return;
            }

            const string baseAddress = "http://www.silenthink.com/html/";
            var routeData = filterContext.Controller.ControllerContext.RouteData;
            if (!string.IsNullOrEmpty(template))
            {
                var uriTemplate = new UriTemplate(template);
                var segmentParams = uriTemplate.PathSegmentVariableNames;
                var dic = new Dictionary<string, string>();

                foreach (var p in segmentParams)
                {
                    var v = routeData.Values[p].ToString();
                    if (!string.IsNullOrEmpty(v))
                    {
                        dic[p] = v;
                    }
                }
                var temp = uriTemplate.BindByName(new Uri(baseAddress), dic);
                filePath = temp.AbsolutePath;
            }
            var token = filePath;

            var clientToken = request.Headers["If-None-Match"];

            if (token == clientToken)
            {
                filterContext.Result = new HttpStatusCodeResult(304);
            }
            else
            {
                filterContext.HttpContext.Response.AddHeader("ETag", token);
            }
        }
    }
}